package org.eva.libra.spring.boot.security.oauth.service;

import java.util.ArrayList;
import java.util.Collection;

import org.eva.libra.spring.boot.security.oauth.domain.OauthAuthority;
import org.eva.libra.spring.boot.security.oauth.domain.OauthUser;
import org.eva.libra.spring.boot.security.oauth.repository.OauthUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component("oauthUserService")
public class OauthUserService implements UserDetailsService {
	@Autowired
	private OauthUserRepository oauthUserRepository;

	@Override
	@Transactional
	public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
		String lowercaseLogin = login.toLowerCase();
		OauthUser oauthUserFromDatabase = oauthUserRepository.findByUsernameCaseInsensitive(lowercaseLogin);

		if (oauthUserFromDatabase == null) {
			throw new UsernameNotFoundException("111");
		}

		// 获取用户的所有权限和SpringSecurity需要的集合
		Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
		for (OauthAuthority authority : oauthUserFromDatabase.getAuthorities()) {
			GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(authority.getName());
			grantedAuthorities.add(grantedAuthority);
		}

		// 返回一个SpringSecurity需要的用户对象
		return new org.springframework.security.core.userdetails.User(oauthUserFromDatabase.getUsername(),
				oauthUserFromDatabase.getPassword(), grantedAuthorities);
	}

}
